package xyz.hubery.service.impl;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import xyz.hubery.feign.JwtToken;
import xyz.hubery.feign.OAuth2FeignClient;
import xyz.hubery.geetest.GeetestLib;
import xyz.hubery.geetest.entity.GeetestLibResult;
import xyz.hubery.service.LoginService;
import xyz.hubery.vo.LoginForm;
import xyz.hubery.vo.LoginUser;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private OAuth2FeignClient oAuth2FeignClient;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private GeetestLib geetestLib;

    @Override
    public LoginUser login(LoginForm loginForm) {
        // 校验表单数据（主要是极验的二次验证）
        loginForm.check(loginForm, geetestLib, redisTemplate);
        // 远程调用获取token
        String basicToken = "Basic " + Base64Utils.encodeToString("coin-api:coin-secret".getBytes());
        ResponseEntity<JwtToken> responseEntity = oAuth2FeignClient.getToken("password", loginForm.getUsername(), loginForm.getPassword(), "member_type",basicToken);
        LoginUser loginUser = null;
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            JwtToken jwtToken = responseEntity.getBody();
            loginUser = new LoginUser(loginForm.getUsername(), jwtToken.getExpiresIn(), jwtToken.getTokenType() + " " + jwtToken.getAccessToken(),jwtToken.getTokenType() + " " + jwtToken.getRefresh_token());
            // 将token保存到redis
            redisTemplate.opsForValue().set(jwtToken.getAccessToken(), "", jwtToken.getExpiresIn(), TimeUnit.SECONDS);
        }
        // 封装登录成功对象
        return loginUser;
    }

}
